import logging
import time
from typing import Dict, Any, List
from config.config_manager import get_hospital_config, get_saas_config
from util.saas_util import SaasUtil, SaasException

logger = logging.getLogger(__name__)


class GetShippingInfoService:
    """收货信息服务类"""

    def __init__(self):
        self.hospital_config = get_hospital_config()
        self.saas_config = get_saas_config()
        self.hospital_name = self.hospital_config.get("name", "医院")

    def get_shipping_info(self, request_params: Dict[str, Any]) -> List[Dict[str, Any]]:
        """获取收货信息

        Args:
            request_params: 请求参数，包括分页和其他可选参数

        Returns:
            List[Dict[str, Any]]: 收货信息列表
        """
        # 1. 获取SaaS配置和token
        user_account = self.saas_config.get("user_account")
        user_password = self.saas_config.get("user_password")

        if not user_account or not user_password:
            raise ValueError("SaaS user_account or user_password 未在 config.yaml 中配置")

        saas_util = SaasUtil()
        token = saas_util.get_access_token(user_account, user_password)
        if not token:
            raise Exception("获取SaaS平台token失败")

        # 2. 构建请求参数
        page_num = request_params.get('page_num', 1)
        page_size = request_params.get('page_size', 5)

        request_data = {
            "currentPageNumber": page_num,
            "size": page_size
        }

        # 添加可选参数
        optional_params = [
            'beginTime', 'endTime', 'incNum', 'ordNos', 'ordDetlCodes',
            'hisOrdNos', 'hisUniqueKeys', 'shpNos', 'shpDetlNos', 'shpStas',
            'entpShpNos', 'entpCodes', 'invoCode', 'invono', 'prodNames',
            'prodentpNames', 'pubonlnProdIDs', 'hisDrugIds', 'stroomId', 'stroomName'
        ]

        for param in optional_params:
            if param in request_params:
                request_data[param] = request_params[param]

        # 3. 调用SaaS接口
        try:
            result = saas_util.get_shipping_information(token, request_data)
            if result and 'resultList' in result:
                return result['resultList']
            else:
                logger.error(f"获取收货信息失败，响应结果: {result}")
                return []
        except SaasException as e:
            logger.error(f"获取收货信息SaaS请求失败: {e}", exc_info=True)
            raise
        except Exception as e:
            logger.error(f"获取收货信息失败: {e}", exc_info=True)
            raise

    def get_all_shipping_info(self) -> List[Dict[str, Any]]:
        """获取所有收货信息（分页获取全部数据）"""
        all_shipping_info = []
        page_num = 1
        page_size = 5

        while True:
            try:
                logger.info(f"开始获取第 {page_num} 页收货信息，每页 {page_size} 条")

                request_params = {
                    'page_num': page_num,
                    'page_size': page_size
                }

                shipping_info = self.get_shipping_info(request_params)

                if not shipping_info:
                    logger.info(f"第 {page_num} 页没有数据，获取完成")
                    break

                all_shipping_info.extend(shipping_info)
                logger.info(f"成功获取第 {page_num} 页数据，共 {len(shipping_info)} 条，累计 {len(all_shipping_info)} 条")

                # 如果获取的数据少于页面大小，说明已经是最后一页
                if len(shipping_info) < page_size:
                    logger.info(f"获取完成，总共 {len(all_shipping_info)} 条收货信息")
                    break

                page_num += 1

                # 批次间延迟，避免请求过于频繁
                time.sleep(0.5)

            except Exception as e:
                logger.error(f"获取第 {page_num} 页收货信息失败: {e}")
                break

        return all_shipping_info


# 创建全局实例
get_shipping_info_service = GetShippingInfoService()


def get_shipping_info(request_params: Dict[str, Any]) -> List[Dict[str, Any]]:
    """获取收货信息（供API调用）"""
    return get_shipping_info_service.get_shipping_info(request_params)


__all__ = ["GetShippingInfoService", "get_shipping_info_service", "get_shipping_info"]